package com.campus.controller;

import com.campus.dto.TeacherUserRequest;
import com.campus.model.Teacher;
import com.campus.service.TeacherService;
import com.campus.web.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/homework/teacher")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    // 新增教师
    @PostMapping("/add")
    public ResponseResult<String> addTeacher(@RequestBody TeacherUserRequest request) {
        boolean result = teacherService.addTeacher(request.getTeacher(), request.getUser());
        if (result) {
            return ResponseResult.ok("Teacher added successfully.");
        } else {
            return ResponseResult.error(HttpStatus.BAD_REQUEST, "Failed to add teacher.");
        }
    }

    @GetMapping("/{id}")
    public ResponseResult<Teacher> getTeacherById(@PathVariable Integer id) {
        Teacher teacher = teacherService.getTeacherById(id);
        if (teacher != null) {
            return ResponseResult.ok(teacher);
        } else {
            return ResponseResult.error(HttpStatus.NOT_FOUND, "Teacher not found.");
        }
    }

    @GetMapping("/search")
    public ResponseResult<List<Teacher>> searchTeachers(
            @RequestParam(required = false) String teacherName,
            @RequestParam(required = false) String subject,
            @RequestParam(required = false) String school) {
        List<Teacher> teachers = teacherService.searchTeachers(teacherName, subject, school);
        return ResponseResult.ok(teachers);
    }

    @PutMapping("/edit/{id}")
    public ResponseResult<String> editTeacher(@PathVariable Integer id, @RequestBody Teacher updatedTeacher) {
        boolean result = teacherService.editTeacher(id, updatedTeacher);
        if (result) {
            return ResponseResult.ok("Teacher edited successfully.");
        } else {
            return ResponseResult.error(HttpStatus.BAD_REQUEST, "Failed to edit teacher.");
        }
    }

    @DeleteMapping("/delete/{id}")
    public ResponseResult<String> deleteTeacher(@PathVariable Integer id) {
        boolean result = teacherService.deleteTeacher(id);
        if (result) {
            return ResponseResult.ok("Teacher deleted successfully.");
        } else {
            return ResponseResult.error(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to delete teacher.");
        }
    }

    // 查询所有教师
    @GetMapping("/list")
    public ResponseResult<List<Teacher>> getAllTeachers() {
        List<Teacher> teachers = teacherService.getAllTeachers();
        if (teachers != null && !teachers.isEmpty()) {
            return ResponseResult.ok(teachers);
        } else {
            return ResponseResult.error(HttpStatus.NOT_FOUND, "No teachers found.");
        }
    }
}
